﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using SqlSugar;
using System.ComponentModel.DataAnnotations.Schema;
using WLYT.Application.Interfaces;
using WLYT.Application.Services;
using WLYT.Domain.Entries;

namespace WLYT.WMS.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ModelDBEntityController(ISqlSugarClient db) : ControllerBase
    {
        /// <summary>
        /// 刷新实体模型
        /// </summary>
        /// <param name="directoryPath">实体类型文件生成路径</param>
        /// <param name="nameSpace">命令空间</param>
        [HttpGet]
        public string RefreshEntity(string directoryPath = @"D:\Git\CAEA\WLYT.WMS\WLYT.Domain\Entries", string nameSpace = "WLYT.Domain.Entries")
        {
            db.DbFirst
                .IsCreateAttribute()
                .IsCreateDefaultValue()
                .SettingPropertyTemplate((columns, temp, type) =>
                {
                    var columnattribute = "\r\n           [SugarColumn({0})]";
                    List<string> attributes = new List<string>();
                    if (columns.IsPrimarykey)
                        attributes.Add("IsPrimaryKey = true");
                    if (columns.IsIdentity)
                        attributes.Add("IsIdentity = true");
                    if (columns.DataType == "varchar" && columns.Length == -1)
                    {
                        attributes.Add("ColumnDataType = StaticConfig.CodeFirst_BigString");
                    }
                    if (attributes.Count == 0)
                    {
                        columnattribute = "";
                    }
                    return temp.Replace("{PropertyType}", type)
                                .Replace("{PropertyName}", columns.DbColumnName)
                                .Replace("{SugarColumn}", string.Format(columnattribute, string.Join(", ", attributes)));
                })
                //.SettingClassDescriptionTemplate(it => { return it + "\r\n    [Tenant(\"db2\")]"; })
                .CreateClassFile(directoryPath, nameSpace);
            return "Success";
        }
    }
}
